<template>
  <div class="count-down">
    <el-button type="text" :disabled="disabled" @click="handleClick">
      {{ text }}
    </el-button>
  </div>
</template>
<script>
export default {
  name: 'CountDown',
  props: {
    action: {
      type: Function,
      default: () => {}
    },
    mobile: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      status: false,
      text: '获取验证码',
      disabled: false
    }
  },
  methods: {
    handleClick() {
      if (!this.mobile) return this.$message.warning('请填写手机号')
      this.status = true
      this.action().then(() => {
        this.$message.success('验证码已发送')
        this.countDown()
      })
    },
    countDown() {
      if (typeof this.text === 'string') {
        this.disabled = true
        this.text = 60
      }

      const fn = setInterval(() => {
        if (this.text === 0) {
          clearInterval(fn)
          this.text = '重新发送'
          this.disabled = false
          return
        }
        this.text--
      }, 1000)

      this.status = false
    }
  }
}
</script>
<style lang="scss">
.count-down {
  .ivu-btn {
    width: 100%;
  }
}
</style>
